<?php
/**
 * 公众号操作类
s * @author lyh/508291869@qq.com
 */
namespace wechat;
class wechat_adv
{
    public $appid = "";
    public $appsecret = "";
    //构造函数，获取Access Token
    public function __construct($appid = NULL, $appsecret = NULL)
    {
        if($appid){
            $this->appid = $appid;
        }
        if($appsecret){
            $this->appsecret = $appsecret;
        }
        
		$file = fopen(dirname(__FILE__)."/tokentime.txt", "r");
		$check=array();
		$i=0;
		//输出文本中所有的行，直到文件结束为止。
		while(! feof($file))
		{
		 $check[$i]= fgets($file);//fgets()函数从文件指针中读取一行
		 $i++;
		}
		$check=array_filter($check);
        //hardcode
        $this->lasttime = $check[0];
        $this->access_token = $check[1];
        
        if (time() > ($this->lasttime + 7200)){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->https_request($url);
            $result = json_decode($res, true);
			$str=array(time(),"\r\n", $result["access_token"]);
			file_put_contents(dirname(__FILE__)."/tokentime.txt", $str);
        }
		fclose($file);
    }

    //获取关注者列表
    public function get_user_list($next_openid = NULL)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    //获取用户基本信息
    public function get_user_info($openid)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    //创建菜单
    public function create_menu($data)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }

    //发送客服消息，已实现发送文本，其他类型可扩展
    public function send_custom_message($touser, $type, $data)
    {
        $msg = array('touser' =>$touser);
        switch($type)
        {
            case 'text':
                $msg['msgtype'] = 'text';
                $msg['text']    = array('content'=> urlencode($data));
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
        return $this->https_request($url, urldecode(json_encode($msg)));
    }

    //生成参数二维码
    public function create_qrcode($scene_type, $scene, $time = 1800)
    {
        switch($scene_type)
        {
            case 'QR_LIMIT_SCENE': //永久
            	$data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$scene.'"}}}';
                break;
            case 'QR_SCENE':       //临时
            	if(!is_numeric($time) || $time > 2592000)
				{
					$time = 1800;
				}
            	$data = '{"expire_seconds": '.$time.', "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$scene.'"}}}';
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        $result = json_decode($res, true);
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result["ticket"]);
    }
    
    //创建分组
    public function create_group($name)
    {
        $data = '{"group": {"name": "'.$name.'"}}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
    
    //移动用户分组
    public function update_group($openid, $to_groupid)
    {
        $data = '{"openid":"'.$openid.'","to_groupid":'.$to_groupid.'}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }
    
    //上传多媒体文件
    public function upload_media($type, $file,$eternal = array())
    {
    	if(count($eternal) <= 0)
		{
			$data = array("media"  => '@'.$file);
	        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
	        $res = $this->https_request($url, $data);
		}
		else
		{
//			$eternal = array(
//				'type' => 'news',//news 图文，newsimg,图文消息图片，order其他(媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）)
//				'file' => 'path',
//				"title":'视频素材的标题',
//				"troduction":'视频素材的描述'
//				'data' => [//多维数组
//					array(
//						"title": '标题',
//						"thumb_media_id": '图文消息的封面图片素材id（必须是永久mediaID）',
//						"author": '作者',
//						"digest": '图文消息的摘要，仅有单图文消息才有摘要，多图文此处为空。如果本字段为没有填写，则默认抓取正文前64个字。',
//						"show_cover_pic": '是否显示封面，0为false，即不显示，1为true，即显示',
//						"content": '图文消息的具体内容，支持HTML标签，必须少于2万字符，小于1M，且此处会去除JS,涉及图片url必须来源 "上传图文消息内的图片获取URL"接口获取。外部图片url将被过滤。',
//						"content_source_url": '图文消息的原文地址，即点击“阅读原文”后的URL',
//						"need_open_comment":'Uint32 是否打开评论，0不打开，1打开',
//						"only_fans_can_comment":'Uint32 是否粉丝才可评论，0所有人可评论，1粉丝才可评论'
//					)
//				]
//			)
			if($eternal['type'] = 'news')
			{
				$news = array('articles'=>$eternal['data']);
				$newsjson = json_encode($news);
				$url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=".$this->access_token;
	        	$res = $this->https_request($url, $newsjsons);
			}
			else if($eternal['type'] = 'newsimg')
			{
				$data = array("media"  => "@".$eternal['file']);
		        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$this->access_token;
		        $res = $this->https_request($url, $data);
			}
			else
			{
				$file = array("media"  => "@".$eternal['file'],"title"=>$eternal['title'],"troduction"=>$eternal['troduction']);
				$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$this->access_token."&type=".$eternal['type'];
	        	$res = $this->https_request($url, $file);
			}
		}
        return json_decode($res, true);
    }
	
	//获取多媒体文件
    public function get_media($media_id,$eternal = false)
    {
    	if($eternal)
		{
			$url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->access_token."&media_id=".$media_id;
	        $res = $this->https_request($url);
		}
		else
		{
	        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->access_token."&media_id=".$media_id;
	        $res = $this->https_request($url);
		}
        return json_decode($res, true);
    }
	
	//删除永久素材文件
    public function del_media($media_id)
    {
    	$url = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token=".$this->access_token."&media_id=".$media_id;
	    $res = $this->https_request($url);
        return json_decode($res, true);
    }
	
	//删除永久图文素材
    public function edit_media($media_arr)
    {
    	$url = "https://api.weixin.qq.com/cgi-bin/material/update_news?access_token=".$this->access_token;
	    $res = $this->https_request($url,$media_arr);
        return json_decode($res, true);
    }
	
	//获取素材总数
    public function get_count()
    {
    	$url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=".$this->access_token;
	    $res = $this->https_request($url);
        return json_decode($res, true);
    }
	
	//获取素材列表
    public function get_list($type = 'news',$offset = 0,$count = 20)
    {
    	$data = array(
			"type"=>$type,
		    "offset"=>$offset,
		    "count"=>$count
		);
    	$url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$this->access_token;
	    $res = $this->https_request($url,$data);
        return json_decode($res, true);
    }
	
    //https请求（支持GET和POST）
    protected function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
        	//处理php版本问题开始
        	if (class_exists('\CURLFile')) {
			    $data['media'] = new \CURLFile(realpath($data['media']));
			} else {
			    if (defined('CURLOPT_SAFE_UPLOAD')) {
			        curl_setopt($curl, CURLOPT_SAFE_UPLOAD, FALSE);
			    }
			}
	        //处理php版本问题结束
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}



//调用方法：

//初始化对象
//$weixin = new wechat_adv("wx633f0087b5f825ae", "d3a42ac9b8b56f23691d63055b73feb6");

//查看Access Token
//var_dump($weixin->access_token);

//创建二维码  返回二维码地址
//echo $weixin->create_qrcode("QR_SCENE", "134324234"); //QR_LIMIT_SCENE永久  QR_SCENE临时

//获取关注者列表
//var_dump($weixin->get_user_list());

//获取用户信息
//$openid = "oLCu61S7Flowrh5SrZLRpTBYmPSU";
//var_dump($weixin->get_user_info($openid));

//创建菜单
//个性化菜单
/*
$data='{
 	"button":[
 	{	
    	"type":"click",
    	"name":"今日歌曲1",
     	"key":"今日歌曲1" 
	},
	{	
    	"type":"click",
    	"name":"今日歌曲2",
     	"key":"今日歌曲2" 
	},
	{	
    	"type":"view",
    	"name":"百度",
     	"url":"https://www.baidu.com/" 
	}
 ]
}';

var_dump($weixin->create_menu($data));
 * 
 */
//用户分组
//var_dump($weixin->create_group("老师"));
//var_dump($weixin->update_group($openid, "100"));

//上传下载多媒体
//var_dump($weixin->upload_media("image","01.jpg"));

//发送客服消息
//var_dump($weixin->send_custom_message('接收用户oppenid', "text", "内容"));